package org.swimv2.sessions;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;
import org.swimv2.entities.Skill;
import org.swimv2.entities.User;
import org.swimv2.interfaces.SearchManagerRemote;

/**
 * Session Bean implementation class SearchManager
 */
@Stateless
@RemoteBinding(jndiBinding="SearchManagerJNDI")
public class SearchManager implements SearchManagerRemote {

	@PersistenceContext(unitName="JPADB")
    private EntityManager manager;

	@Override
	public User getUserById(int id) {
		User u;
		
		try {
			Query q = manager.createNamedQuery("User.getUserById");
			q.setParameter("id", id);
			u = (User) q.getSingleResult();
		}
		catch (Exception e) {
			return null;
		}
		return u;
	}
	
	
	@Override
	public List<User> searchForName(String name) {
		List<User> res;
		try {
			Query q = manager.createNamedQuery("User.searchForName");
			q.setParameter("name", name);
			res = (List<User>) q.getResultList();
		}
		catch (Exception e) {
			return null;
		}
		return res;
	}

	@Override
	public List<User> searchForSkill(Skill skill) {
		List<User> res;
		try {
			Query q = manager.createNamedQuery("User.searchForSkill");
			q.setParameter("skill", skill);
			res = (List<User>) q.getResultList();
		}
		catch (Exception e) {
			return null;
		}
		return res;
	}

	
	@Override
	public List<User> searchFriendsForSkill(User user, Skill skill) {
		List<User> res;
		List<User> usersNotFriend;
		
		try {
			Query q = manager.createNamedQuery("User.searchForSkill");
			q.setParameter("skill", skill);
			res = (List<User>) q.getResultList();
			
			Query q1 = manager.createNamedQuery("User.searchUserNotFriend");
			q1.setParameter("user", user);
			usersNotFriend = (List<User>) q1.getResultList();
			
			res.removeAll(usersNotFriend);
		
		}
		catch (Exception e) {
			return null;
		}
		return res;
	}

}
